import { ref } from 'vue'
import { defineStore } from 'pinia'
import type { RouteRecordRaw } from 'vue-router'
import type { MenuTree } from '@/api/auth'

// 动态路由配置
const asyncRoutes: RouteRecordRaw[] = [
  {
    path: '/system',
    component: () => import('@/layouts/Layout.vue'),
    redirect: '/system/user',
    meta: { title: '系统管理', icon: 'Setting' },
    children: [
      {
        path: 'user',
        name: 'User',
        component: () => import('@/views/system/user/index.vue'),
        meta: { title: '用户管理', icon: 'User' }
      },
      {
        path: 'role',
        name: 'Role',
        component: () => import('@/views/system/role/index.vue'),
        meta: { title: '角色管理', icon: 'UserFilled' }
      },
      {
        path: 'menu',
        name: 'Menu',
        component: () => import('@/views/system/menu/index.vue'),
        meta: { title: '菜单管理', icon: 'Menu' }
      },
      {
        path: 'permission',
        name: 'Permission',
        component: () => import('@/views/system/permission/index.vue'),
        meta: { title: '权限管理', icon: 'Lock' }
      }
    ]
  }
]

export const usePermissionStore = defineStore('permission', () => {
  const routes = ref<RouteRecordRaw[]>([])
  const addRoutes = ref<RouteRecordRaw[]>([])
  const menus = ref<MenuTree[]>([])

  // 根据菜单生成路由
  function generateRoutes(userMenus: MenuTree[]): RouteRecordRaw[] {
    menus.value = userMenus

    // 调试信息
    console.log('用户菜单数据:', userMenus)
    console.log('静态路由配置:', asyncRoutes)

    // 这里可以根据后端返回的菜单动态生成路由
    // 目前先使用静态路由配置
    const accessedRoutes = filterAsyncRoutes(asyncRoutes, userMenus)

    console.log('过滤后的路由:', accessedRoutes)

    addRoutes.value = accessedRoutes
    routes.value = [...routes.value, ...accessedRoutes]

    return accessedRoutes
  }

  // 过滤异步路由
  function filterAsyncRoutes(routes: RouteRecordRaw[], menus: MenuTree[]): RouteRecordRaw[] {
    const res: RouteRecordRaw[] = []

    routes.forEach(route => {
      const tmp = { ...route }

      // 检查是否有权限访问该路由
      if (hasPermission(menus, tmp)) {
        if (tmp.children) {
          tmp.children = filterAsyncRoutes(tmp.children, menus)
        }
        res.push(tmp)
      }
    })

    return res
  }

  // 检查权限
  function hasPermission(menus: MenuTree[], route: RouteRecordRaw): boolean {
    // 对于系统管理这样的父级路由，如果有任何子菜单权限就允许访问
    if (route.children && route.children.length > 0) {
      const hasChildAccess = route.children.some(child => hasPermission(menus, child))
      console.log(`检查父级路由权限: ${route.name} -> ${hasChildAccess}`)
      return hasChildAccess
    }

    // 对于具体的页面路由，检查菜单权限
    if (route.name) {
      const hasAccess = hasMenuPermission(menus, route.name as string)
      console.log(`检查路由权限: ${route.name} -> ${hasAccess}`)
      return hasAccess
    }
    return true
  }

  // 递归检查菜单权限
  function hasMenuPermission(menus: MenuTree[], routeName: string): boolean {
    for (const menu of menus) {
      console.log(`比较菜单: ${menu.name} vs 路由: ${routeName}`)
      if (menu.name === routeName) {
        console.log(`✅ 找到匹配的菜单: ${menu.name}`)
        return true
      }
      if (menu.children && menu.children.length > 0) {
        console.log(`🔍 检查 ${menu.name} 的子菜单...`)
        if (hasMenuPermission(menu.children, routeName)) {
          return true
        }
      }
    }
    return false
  }

  // 重置路由
  function resetRoutes() {
    routes.value = []
    addRoutes.value = []
    menus.value = []
  }

  return {
    routes,
    addRoutes,
    menus,
    generateRoutes,
    resetRoutes
  }
})
